package com.example.chessbattleplatform.Interceptor;

import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class WebSocketSetUserConfigurator extends ServerEndpointConfig.Configurator {

    // 注入 GetUserTokenInterceptorInformation 类

    private static GetUserTokenInterceptorInformation getUserTokenInterceptorInformation;

    @Autowired
    public void setGetUserTokenInterceptorInformation(GetUserTokenInterceptorInformation getUserTokenInterceptorInformation) {
        WebSocketSetUserConfigurator.getUserTokenInterceptorInformation = getUserTokenInterceptorInformation;
    }

    /**
     * webSocket 建立握手时，连接前的操作
     */
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {

        //获取 获取标头
        Map<String, List<String>> headers = request.getHeaders();

        List<String> strings = Objects.isNull(headers.get("Sec-WebSocket-Protocol")) ? headers.get("Authorization") : headers.get("Sec-WebSocket-Protocol");

        String token = strings.stream().filter(s -> s.startsWith("Bearer"))  // 先过滤出以 "Bearer" 开头的
                .map(s -> s.replaceFirst("Bearer[,\\s]+", ""))  // 移除 "Bearer" 及后面的逗号/空格
                .findFirst().orElse(null);

//        log.info("token {},headers {}", token, strings);

        String userTokenId = getUserTokenInterceptorInformation.getUserTokenId(token);

        // 将token存储到用户属性中
        sec.getUserProperties().put("user_Id", userTokenId);

        // 获取 Sec-WebSocket-Protocol 头
        // 谷歌浏览器传这个值了。加个判断最终解决。
        List<String> protocols = headers.get("Sec-WebSocket-Protocol");

        if (protocols != null && !protocols.isEmpty()) {
            // 随便指定一个值，因为谷歌浏览器会报错，所以这里随便指定一个值
            response.getHeaders().put("Sec-WebSocket-Protocol", Collections.singletonList("Bearer"));
        }
    }

    /**
     * 初始化端点对象,也就是被@ServerEndpoint所标注的对象
     */
    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return super.getEndpointInstance(clazz);
    }

}
